﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using CSP.Model.CSPEnum;
using CSP.Common.Web;
using CSP.Model.CSP;
using CSP.Common.Tools;
using CSP.Bll.DTO.Order;
using CSP.Web.Master;
using CSP.Web.UserControls;

namespace CSP.Web.MyHome.ConsumeOrder
{
    public partial class CreateOrder : CSPMyHome
    {
        private string _contactWayJson = "{}";

        private string _authenticationStyle = "";

        private string _authenticationName = "";

        #region 属性
        /// <summary>
        /// 认证样式
        /// </summary>
        protected string AuthenticationStyle
        {
            get
            {
                return _authenticationStyle;
            }

        }

        /// <summary>
        /// 认证名称
        /// </summary>
        protected string AthenticationName
        {
            get
            {
                return _authenticationName;
            }
        }

        public string ContactWayJson
        {
            get
            {
                return _contactWayJson;
            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Request["surplusenjoycount_id"] != null)
                {
                    int surplusEnjoyCount = GetSurplusEnjoyCountById(Convert.ToInt32(Request["SurplusEnjoyCount_Id"].ToString()));
                    Response.ClearContent();
                    Response.ContentType = "text/plain";
                    Response.Write(surplusEnjoyCount);
                    Response.End();
                }
                PageInit();
            }
        }

        private void PageInit()
        {
            if (Request["id"] == null)
            {
                LoggerProvider.Error("请求的Id不存在/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息不存在", "/Index.aspx");
            }
            CSP.Model.CSP.ServiceInfo serviceInfo = GetServiceInfoById(Convert.ToInt32(Request["id"].ToString()));

            if (serviceInfo == null)
            {
                LoggerProvider.Error("请求的课程不存在" + Request["id"].ToString() + "/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息已经下架,请选择其他信息", "/Index.aspx");
            }

            if (Convert.ToInt32(serviceInfo.status) != (int)ServiceInfoStatus.OnLine)
            {
                LoggerProvider.Error(Request["id"].ToString() + "/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息已经下架", "/Index.aspx");
            }
            if(serviceInfo.username==this.UserProvider.UserName){
                this.FailRedirect("不能对自己所属的课程预约", "/Index.aspx");
            }
            BindServiceInfoUI(serviceInfo);
            SetContactWay(serviceInfo.username);
        }

        /// <summary>
        /// 绑定服务UI 信息
        /// </summary>
        /// <param name="serviceInfo"></param>
        private void BindServiceInfoUI(CSP.Model.CSP.ServiceInfo serviceInfo)
        {
            this.LB_Title.Text = serviceInfo.title;
            this.LB_Price.Text = serviceInfo.Price.ToString("0.00");
            this.LB_OriginalPrice.Text = serviceInfo.OriginalPrice.Value.ToString("0.00");
            this.LB_PriceUnit.Text = serviceInfo.PriceUnit.name;
            this.LB_OriginalPriceUnit.Text = serviceInfo.OriginalPriceUnit.name;
            this.LB_Price.Text = GetPriceByPriceTypeAndPriceAndPriceStartAndPriceEnd((int)serviceInfo.PriceType, serviceInfo.Price, serviceInfo.PriceStart, serviceInfo.PriceEnd);
            this.LB_ClassOfMemberNumber.Text = serviceInfo.ClassOfMemberNumber.ToString();
            this.LB_UserName.Text = serviceInfo.username;

            this.LB_Province.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_Province;
            this.LB_City.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_City;
            this.LB_County.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_County;
            this.LB_Street.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Street;

            UserBasic userBasic = GetUserBasicInfoByUser(serviceInfo.username);
            _authenticationName = GetCNNameByAuthentication(userBasic.PersonalAuthentication, userBasic.EnterpriseAuthentication);
            _authenticationStyle = GetStyleByAuthentication(userBasic.PersonalAuthentication, userBasic.EnterpriseAuthentication);

        }

        /// <summary>
        /// 设置联系方式
        /// </summary>
        private void SetContactWay(string userName)
        {
            ICollection<Model.CSP.ContactWay> contactWays = GetContactWaysByUser(userName);

            if (contactWays == null || contactWays.Count == 0)
            {
                return;
            }

            ContactWayUI[] contactWayUI = (from contact in contactWays
                                           select new ContactWayUI
                                           {
                                               Address = contact.address,
                                               Type = contact.type
                                           }).ToArray();
            _contactWayJson = CommonTool.SerializeObject(contactWayUI);
        }

        /// <summary>
        /// 根据Id获取服务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private CSP.Model.CSP.ServiceInfo GetServiceInfoById(int id)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceInfo result = null;
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataById(id);
            }
            return result;
        }

        /// <summary>
        /// 根据用户获取用户基本信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private UserBasic GetUserBasicInfoByUser(string userName)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.UserBasic result = null;
            using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
            {
                result = userInfoBll.GetUserBasicByUser(userName);
            }
            return result;
        }

        /// <summary>
        /// 根据User获取联系方式
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private ICollection<Model.CSP.ContactWay> GetContactWaysByUser(string userName)
        {
            ICollection<Model.CSP.ContactWay> result = null;
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            using (IContactWayBll contactWayBll = factory.GetContactWayBll())
            {
                result = contactWayBll.FindByUser(userName);
            }

            return result;
        }

        /// <summary>
        /// 根据认证类型和认证状态获取 当前认证名称
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetCNNameByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "企业认证";
            }

            if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "个人认证";
            }

            return "未认证";
        }

        /// <summary>
        /// 获取样式根据企业认证和个人认证 状态
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetStyleByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            //企业认证
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-enterprise";
            }

            //个人认证
            else if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-personal";
            }
            else
            {
                return "i-v-unautherized";
            }
        }

        /// <summary>
        /// 根据价格类型，现价格，最低价格，最高价格，获取价格
        /// </summary>
        /// <param name="priceType"></param>
        /// <param name="price"></param>
        /// <param name="priceStart"></param>
        /// <param name="priceEnd"></param>
        /// <returns></returns>
        private string GetPriceByPriceTypeAndPriceAndPriceStartAndPriceEnd(int priceType, decimal price, decimal priceStart, decimal priceEnd)
        {
            string result = "";
            if ((PriceType)priceType == PriceType.FixedPrice) //一口价
            {
                result = price.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.PriceRange)//价格范围
            {
                result = priceStart.ToString("0.00") + "--" + priceEnd.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.Negotiable)//面议
            {
                result = "面议";
            }
            return result;
        }

        /// <summary>
        /// 将UI填写信息,生成Order订单对象
        /// </summary>
        /// <returns></returns>
        private Order GetOrderInfoByUI()
        {
            Order order = new Order();
            //order.ServiceUserName = serviceUserName;
            order.OrderUserName = UserProvider.UserName;
            order.ContactedMan = this.Txt_ContactedMan.Value.Trim();
            order.Phone = this.Txt_Phone.Value.Trim();
            order.Email = this.Txt_Email.Value.Trim();
            order.AppointmentDate = Convert.ToDateTime(this.Txt_AppointmentDate.Text.Trim());
            order.Address = this.Txt_Adress.Value;
            order.PaymentStatus = 0;
            order.OrderTime = DateTime.Now;
            order.ServiceInfoId = Convert.ToInt32(Request["id"]);
            string[] students = this.Txt_Students.Value.Split(',');
            List<StudentInfo> studentinfoes = new List<StudentInfo>();
            for (int i = 0; i < students.Length; i++)
            {
                string name = students[i].Split('|')[0];
                string email = students[i].Split('|')[1];
                StudentInfo studentInfo = new StudentInfo
                {
                    Name = name,
                    Email = email
                };
                studentinfoes.Add(studentInfo);
            }
            order.StudentInfoes = studentinfoes;
            return order;
        }

        private int GetSurplusEnjoyCountById(int id)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            int result = 0;
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                result = serviceInfoBll.GetSurplusEnjoyCountById(id);
            }
            return result;
        }

        protected void Btn_Submit_Click(object sender, EventArgs e)
        {
            Order order = GetOrderInfoByUI();
            CreateOrderResponseDTO result = null;
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            try
            {
                using (IOrderBll orderBll = factory.GetOrderBll())
                {
                    result = orderBll.CreateOrder(order);
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error("请求的Id不存在/MyHome/ServiceInfo/List.aspx", ex);
                this.FailRedirect("您所创建订单失败了", "/");
            }

            if (result.Status == CreateOrderStatus.SuccessFully)
            {
                //订单创建成功
                Response.Redirect("OrderOK.aspx?id=" + Request["id"].ToString());
            }
            else if (result.Status == CreateOrderStatus.None)
            {
                LoggerProvider.Error("请求的Id不存在/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息不存在,无法创建订单", "/");
            }
            else if (result.Status == CreateOrderStatus.OffLined)
            {
                LoggerProvider.Error("请求的Id不存在/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息已经下架,无法创建订单", "/");
            }
            else if (result.Status == CreateOrderStatus.ServiceShortage)
            {
                LoggerProvider.Error("请求的Id不存在/MyHome/ServiceInfo/List.aspx");
                this.FailRedirect("您请求的课程信息接纳量不足,无法创建订单", "/");
            }

        }

        private class ContactWayUI
        {
            public string Address { get; set; }

            public int Type { get; set; }
        }
    }
}